# -*- coding: utf-8 -*-
from django.shortcuts import render,redirect,reverse
from django.views.decorators.csrf import ensure_csrf_cookie
from django.views.decorators.csrf import csrf_exempt,csrf_protect
from django.middleware.csrf import get_token

from django.http import JsonResponse
from django.views.decorators.http import require_GET,require_POST, require_http_methods
from rest_framework.generics import ListAPIView
from django.views import View
from django.utils.decorators import method_decorator
import logging

from .serializer import UserSerializers
from .models import User
from .forms import HomeForm

from teat_demo.core.exceptions.base import ValidtorsException

logger = logging.getLogger('console')

# Create your views here.
"""
特殊装饰器：CSRF Token只能加到dispatch（django的bug）

CBV的csrf装饰器需要导入

from django.views.decorators.csrf import csrf_exempt,csrf_protect
 
csrf_exempt是全局需要，唯独这个不需要
csrf_protect是全局不需要，唯独这个需要
作用：
    比如首页 可以使用csrf_exempt不做token校验通俗的说可以通过csrf中间件
"""


# ----------------------FBV-----------------------
@ensure_csrf_cookie
def get_csrf_token(request):
    return JsonResponse({})


@require_GET
def home(request):
    
    context = {
        "hello":'您好'
    }
    request.session['is_login'] = True

    user_querset = User.users.all()
    if user_querset:
        context.update({'data':user_querset})
    return render(request,'home/home.html', context)


# @csrf_exempt
@require_http_methods(['POST','GET'])
def add_users(request):
    _ = HomeForm()
    if request.method =='POST':
        data = request.POST
        print(data,'test')
        check_value = HomeForm(data)
        if check_value.is_valid():
            if check_value.save():
                return JsonResponse({'result': False,'code':'500','errmsg':'重复添加'})
            return redirect(reverse('home'))
            # return JsonResponse({'result':True,'code':'201','errmsg':'OK'})
        else:
            return JsonResponse({'result':False,'code':'500','errmsg':'添加失败'})
    elif request.method == 'GET':
        users = User.users.all()
        csrf_token = get_token(request)
        data = [{'username':user.username,'id':user.id,'age':user.age,'active':user.active} for user in users]
        return JsonResponse({'result':True,'code':'200','data':data,'csrf_token':csrf_token})
    else:
        return JsonResponse({'result':False,'code':'500','errmsg':'请求方式问题'})

@require_GET
def test_exceptions(request):
    # _ = 1/0
    # raise  ValidtorsException()
    # 测试 ES的查询
    logger.debug('aaaaaa')
    logger.info('bbbbbbb')
    logger.warn('ccccccc')
    logger.error('dddddddd')
    return JsonResponse({'result':True,'code':200,'errmsg':'OK'})

# @csrf_exempt
@require_http_methods(['POST'])
def test_post(request):
    """
    测试vue-cli 的post请求
    """
    print(request.body)
    return JsonResponse({'result':True,'code':200,'errmsg':'OK'})

# ----------------------CBV-----------------------

class Home(ListAPIView): # 用到rest_framework
    # return MVC 
    queryset = User.users.all()
    serializer_class = UserSerializers    



# +++++++++++++++++++++++++++++++++++++++++++++++++++
def test(func):
    def inner(*args,**kwargs):
        return func(*args,**kwargs)
    return inner

@method_decorator(test,name='get') # Django 内置的装饰器，name是指定要装饰的方法，test就是装饰器的引用
class TestDecorator(View):
    def get(self,request):
        # 测试自定义信号 <可以是同步，可以是异步>
        from teat_demo.signals import pizza_done
        # 可以接受结果判断是否同步成功，如果异步的话，需要自己重新自定义个监控的脚本来处理把结果写入到日志
        result = pizza_done.send(sender='seven',toppings=123,size=34)
        print('result',result)
        return JsonResponse({'result':True,'code':200,'errmsg':'OK'})

# +++++++++++++++++++++++++++++++++++++++++++++++++++
# 集成GraphQL API 
